package Pet.Management.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import Pet.Management.domain.dto.PostDTO;
import Pet.Management.domain.dto.UserDTO;
import Pet.Management.domain.entity.Comment;
import Pet.Management.domain.entity.Favorite;
import Pet.Management.domain.entity.Like;
import Pet.Management.domain.entity.PetFinder;
import Pet.Management.domain.entity.Post;
import Pet.Management.domain.entity.Tag;
import Pet.Management.domain.entity.User;
import Pet.Management.repository.CommentRepository;
import Pet.Management.repository.FavoriteRepository;
import Pet.Management.repository.LikeRepository;
import Pet.Management.repository.PetFinderRepository;
import Pet.Management.repository.PostRepository;
import Pet.Management.repository.TagRepository;
import Pet.Management.repository.UserRepository;
import Pet.Management.service.FileStorageService;
import Pet.Management.service.MessageService;

@RestController
@RequestMapping("/api/community")
public class CommunityController {

    @Autowired
    private PostRepository postRepository;
    
    @Autowired
    private TagRepository tagRepository;
    
    @Autowired
    private CommentRepository commentRepository;
    
    @Autowired
    private LikeRepository likeRepository;
    
    @Autowired
    private FavoriteRepository favoriteRepository;
    
    @Autowired
    private PetFinderRepository petFinderRepository;
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private FileStorageService fileStorageService;
    
    @Autowired
    private MessageService messageService;
    
    /**
     * 获取帖子列表
     */
    @GetMapping("/posts")
    public ResponseEntity<Map<String, Object>> getPosts(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "newest") String sort,
            @RequestParam(required = false) String search,
            @RequestParam(required = false) Long userId,
            @RequestHeader(value = "Authorization", required = false) String token) {
        
        System.out.println("获取帖子列表请求: page=" + page + ", size=" + size + ", sort=" + sort + 
                         ", search=" + search + ", userId=" + userId + ", token=" + token);
        
        Pageable pageable = PageRequest.of(page, size);
        Page<Post> postPage;
        
        if (search != null && !search.isEmpty()) {
            postPage = postRepository.searchPosts(search, pageable);
        } else if ("hottest".equals(sort)) {
            postPage = postRepository.findHottestPosts(pageable);
        } else {
            postPage = postRepository.findLatestPosts(pageable);
        }
        
        Long currentUserId = null;
        
        // 首先尝试从请求参数中获取用户ID
        if (userId != null) {
            System.out.println("使用请求参数中的userId: " + userId);
            Optional<User> userOpt = userRepository.findById(userId);
            if (userOpt.isPresent()) {
                currentUserId = userId;
                System.out.println("成功找到用户ID: " + currentUserId);
            } else {
                System.out.println("找不到指定ID的用户: " + userId);
            }
        }
        
        // 如果请求参数中没有有效的用户ID，尝试从token中获取
        if (currentUserId == null && token != null && !token.isEmpty()) {
            System.out.println("尝试从token获取用户信息: " + token);
            
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
                System.out.println("处理Bearer token: " + token);
            }
            
            try {
                // 尝试将token解析为用户ID
                Long tokenUserId = Long.parseLong(token);
                Optional<User> currentUser = userRepository.findById(tokenUserId);
                if (currentUser.isPresent()) {
                    currentUserId = tokenUserId;
                    System.out.println("从token中解析出用户ID: " + currentUserId);
                }
            } catch (NumberFormatException e) {
                // 如果token不是数字，尝试作为用户名查找
                Optional<User> currentUser = userRepository.findByUsername(token);
                if (currentUser.isPresent()) {
                    currentUserId = currentUser.get().getId();
                    System.out.println("通过用户名找到用户ID: " + currentUserId);
                }
            }
        }
        
        System.out.println("最终使用的用户ID: " + currentUserId);
        
        final Long finalCurrentUserId = currentUserId;
        List<PostDTO> postDTOs = postPage.getContent().stream().map(post -> {
            PostDTO dto = convertToDTO(post);
            
            // 设置用户是否点赞和收藏
            if (finalCurrentUserId != null) {
                Optional<Like> like = likeRepository.findByUserIdAndPostId(finalCurrentUserId, post.getId());
                dto.setIsLiked(like.isPresent());
                
                Optional<Favorite> favorite = favoriteRepository.findByUserIdAndPostId(finalCurrentUserId, post.getId());
                dto.setIsFavorited(favorite.isPresent());
                
                System.out.println("帖子ID: " + post.getId() + ", 用户ID: " + finalCurrentUserId + 
                               ", 点赞状态: " + like.isPresent() + ", 收藏状态: " + favorite.isPresent());
            } else {
                dto.setIsLiked(false);
                dto.setIsFavorited(false);
            }
            
            return dto;
        }).collect(Collectors.toList());
        
        Map<String, Object> response = Map.of(
            "posts", postDTOs,
            "currentPage", postPage.getNumber(),
            "totalItems", postPage.getTotalElements(),
            "totalPages", postPage.getTotalPages()
        );
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 获取帖子详情
     */
    @GetMapping("/posts/{id}")
    @Transactional
    public ResponseEntity<PostDTO> getPostDetail(
            @PathVariable Long id,
            @RequestParam(required = false) Long userId,
            @RequestHeader(value = "Authorization", required = false) String token) {
        
        System.out.println("获取帖子详情请求: postId=" + id + ", userId=" + userId + ", token=" + token);
        
        Optional<Post> postOpt = postRepository.findById(id);
        if (!postOpt.isPresent()) {
            return ResponseEntity.notFound().build();
        }
        
        Post post = postOpt.get();
        
        // 增加浏览量
        postRepository.incrementViewCount(id);
        
        PostDTO postDTO = convertToDTO(post);
        
        Long currentUserId = null;
        
        // 首先尝试从请求参数中获取用户ID
        if (userId != null) {
            System.out.println("使用请求参数中的userId: " + userId);
            Optional<User> userOpt = userRepository.findById(userId);
            if (userOpt.isPresent()) {
                currentUserId = userId;
                System.out.println("成功找到用户ID: " + currentUserId);
            } else {
                System.out.println("找不到指定ID的用户: " + userId);
            }
        }
        
        // 如果请求参数中没有有效的用户ID，尝试从token中获取
        if (currentUserId == null && token != null && !token.isEmpty()) {
            System.out.println("尝试从token获取用户信息: " + token);
            
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
                System.out.println("处理Bearer token: " + token);
            }
            
            try {
                // 尝试将token解析为用户ID
                Long tokenUserId = Long.parseLong(token);
                Optional<User> currentUser = userRepository.findById(tokenUserId);
                if (currentUser.isPresent()) {
                    currentUserId = tokenUserId;
                    System.out.println("从token中解析出用户ID: " + currentUserId);
                }
            } catch (NumberFormatException e) {
                // 如果token不是数字，尝试作为用户名查找
                Optional<User> currentUser = userRepository.findByUsername(token);
                if (currentUser.isPresent()) {
                    currentUserId = currentUser.get().getId();
                    System.out.println("通过用户名找到用户ID: " + currentUserId);
                }
            }
        }
        
        // 设置用户是否点赞和收藏
        if (currentUserId != null) {
            Optional<Like> like = likeRepository.findByUserIdAndPostId(currentUserId, post.getId());
            postDTO.setIsLiked(like.isPresent());
            
            Optional<Favorite> favorite = favoriteRepository.findByUserIdAndPostId(currentUserId, post.getId());
            postDTO.setIsFavorited(favorite.isPresent());
            
            System.out.println("帖子详情 - 帖子ID: " + id + ", 用户ID: " + currentUserId + 
                           ", 点赞状态: " + like.isPresent() + ", 收藏状态: " + favorite.isPresent());
        } else {
            postDTO.setIsLiked(false);
            postDTO.setIsFavorited(false);
            System.out.println("帖子详情 - 帖子ID: " + id + ", 无用户信息，默认未点赞未收藏");
        }
        
        return ResponseEntity.ok(postDTO);
    }
    
    /**
     * 创建帖子
     */
    @PostMapping("/posts")
    @Transactional
    public ResponseEntity<PostDTO> createPost(
            @RequestBody Map<String, Object> payload) {
        
        // 处理userId的类型转换
        Object userIdObj = payload.get("userId");
        Long userId;
        if (userIdObj instanceof Integer) {
            userId = ((Integer) userIdObj).longValue();
        } else if (userIdObj instanceof Long) {
            userId = (Long) userIdObj;
        } else {
            return ResponseEntity.badRequest().build();
        }
        
        Optional<User> userOpt = userRepository.findById(userId);
        if (!userOpt.isPresent()) {
            return ResponseEntity.badRequest().build();
        }
        User user = userOpt.get();
        
        String title = (String) payload.get("title");
        String content = (String) payload.get("content");
        
        @SuppressWarnings("unchecked")
        List<String> tagNames = (List<String>) payload.get("tags");
        
        Post post = new Post();
        post.setTitle(title);
        post.setContent(content);
        post.setUser(user);
        
        Post savedPost = postRepository.save(post);
        
        // 处理标签
        if (tagNames != null && !tagNames.isEmpty()) {
            List<Tag> tags = new ArrayList<>();
            
            for (String tagName : tagNames) {
                Optional<Tag> existingTag = tagRepository.findByName(tagName);
                Tag tag;
                
                if (existingTag.isPresent()) {
                    tag = existingTag.get();
                } else {
                    tag = new Tag();
                    tag.setName(tagName);
                    tag = tagRepository.save(tag);
                }
                
                tags.add(tag);
            }
            
            savedPost.setTags(tags);
            savedPost = postRepository.save(savedPost);
        }
        
        return ResponseEntity.ok(convertToDTO(savedPost));
    }
    
    /**
     * 点赞/取消点赞帖子
     */
    @PostMapping("/posts/{id}/like")
    @Transactional
    public ResponseEntity<Map<String, Object>> likePost(
            @PathVariable Long id,
            @RequestParam Long userId) {
        
        Optional<User> userOpt = userRepository.findById(userId);
        if (!userOpt.isPresent()) {
            return ResponseEntity.badRequest().build();
        }
        
        return processLikePost(id, userOpt.get());
    }
    
    /**
     * 处理点赞/取消点赞的核心逻辑
     */
    private ResponseEntity<Map<String, Object>> processLikePost(Long postId, User user) {
        Optional<Post> postOpt = postRepository.findById(postId);
        if (!postOpt.isPresent()) {
            return ResponseEntity.notFound().build();
        }
        
        Post post = postOpt.get();
        Optional<Like> existingLike = likeRepository.findByUserIdAndPostId(user.getId(), post.getId());
        boolean isLiked;
        
        try {
            if (existingLike.isPresent()) {
                // 取消点赞
                likeRepository.delete(existingLike.get());
                
                // 确保点赞数不会小于0
                if (post.getLikeCount() > 0) {
                    postRepository.updateLikeCount(post.getId(), -1);
                }
                isLiked = false;
                System.out.println("用户 " + user.getId() + " 取消点赞帖子 " + postId);
            } else {
                // 点赞
                Like like = new Like();
                like.setUser(user);
                like.setPost(post);
                likeRepository.save(like);
                postRepository.updateLikeCount(post.getId(), 1);
                isLiked = true;
                System.out.println("用户 " + user.getId() + " 点赞帖子 " + postId);
                
                // 发送点赞通知
                messageService.sendLikeNotification(user, postId);
            }
            
            // 查询最新的点赞数，确保数据准确
            post = postRepository.findById(postId).orElse(post);
            
            // 再次检查确保点赞数不为负数
            if (post.getLikeCount() < 0) {
                post.setLikeCount(0);
                postRepository.save(post);
                System.out.println("修正帖子 " + postId + " 的点赞数为0");
            }
            
            // 计算实际的点赞数，作为额外验证
            long actualLikeCount = likeRepository.countByPostId(postId);
            if (actualLikeCount != post.getLikeCount()) {
                System.out.println("帖子 " + postId + " 的点赞数不一致，数据库中显示" + 
                               post.getLikeCount() + "，实际点赞数为" + actualLikeCount);
                post.setLikeCount((int)actualLikeCount);
                postRepository.save(post);
            }
            
            return ResponseEntity.ok(Map.of(
                "likeCount", post.getLikeCount(),
                "isLiked", isLiked
            ));
        } catch (Exception e) {
            System.err.println("处理点赞操作时发生错误: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(500).body(Map.of(
                "error", "处理点赞操作时发生错误",
                "message", e.getMessage()
            ));
        }
    }
    
    /**
     * 提交AI寻宠请求
     */
    @PostMapping("/pet-finder")
    public ResponseEntity<PetFinder> submitPetFinder(
            @RequestParam(required = false) MultipartFile image,
            @RequestParam String description,
            @RequestParam Long userId) {
        
        Optional<User> userOpt = userRepository.findById(userId);
        if (!userOpt.isPresent()) {
            return ResponseEntity.badRequest().build();
        }
        User user = userOpt.get();
        
        PetFinder petFinder = new PetFinder();
        petFinder.setUser(user);
        petFinder.setDescription(description);
        petFinder.setStatus(0); // 待处理
        
        // 处理图片上传
        if (image != null && !image.isEmpty()) {
            String imageUrl = fileStorageService.storeFile(image, "petfinder");
            petFinder.setImageUrl(imageUrl);
        }
        
        PetFinder savedPetFinder = petFinderRepository.save(petFinder);
        
        return ResponseEntity.ok(savedPetFinder);
    }
    
    /**
     * 将Post实体转换为PostDTO
     */
    private PostDTO convertToDTO(Post post) {
        PostDTO dto = new PostDTO();
        dto.setId(post.getId());
        dto.setTitle(post.getTitle());
        dto.setContent(post.getContent());
        
        UserDTO authorDTO = new UserDTO();
        authorDTO.setId(post.getUser().getId());
        authorDTO.setUsername(post.getUser().getUsername());
        authorDTO.setNickname(post.getUser().getNickname());
        authorDTO.setAvatar(post.getUser().getAvatar());
        dto.setAuthor(authorDTO);
        
        dto.setViewCount(post.getViewCount());
        dto.setLikeCount(post.getLikeCount());
        dto.setFavoriteCount(post.getFavoriteCount());
        dto.setCommentCount(post.getCommentCount());
        dto.setStatus(post.getStatus());
        dto.setCreateTime(post.getCreateTime());
        dto.setUpdateTime(post.getUpdateTime());
        
        // 处理标签
        if (post.getTags() != null) {
            List<String> tagNames = post.getTags().stream()
                .map(Tag::getName)
                .collect(Collectors.toList());
            dto.setTags(tagNames);
        } else {
            dto.setTags(new ArrayList<>());
        }
        
        // 默认初始化点赞和收藏状态为false，避免空值
        dto.setIsLiked(false);
        dto.setIsFavorited(false);
        
        return dto;
    }

    /**
     * 获取用户自己的帖子列表
     */
    @GetMapping("/my-posts")
    public ResponseEntity<Map<String, Object>> getMyPosts(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String status,
            @RequestParam Long userId) {
        
        Optional<User> userOpt = userRepository.findById(userId);
        if (!userOpt.isPresent()) {
            return ResponseEntity.badRequest().build();
        }
        
        return getPostsByUser(page, size, status, userOpt.get());
    }
    
    /**
     * 根据用户获取帖子列表
     */
    private ResponseEntity<Map<String, Object>> getPostsByUser(int page, int size, String status, User user) {
        final Long userId = user.getId();
        
        Pageable pageable = PageRequest.of(page, size);
        Page<Post> postPage;
        
        if (status != null && !status.isEmpty() && !"all".equals(status)) {
            postPage = postRepository.findByUserIdAndStatus(userId, status, pageable);
        } else {
            postPage = postRepository.findByUserId(userId, pageable);
        }
        
        List<PostDTO> postDTOs = postPage.getContent().stream().map(post -> {
            PostDTO dto = convertToDTO(post);
            
            // 设置用户是否点赞和收藏
            Optional<Like> like = likeRepository.findByUserIdAndPostId(userId, post.getId());
            dto.setIsLiked(like.isPresent());
            
            Optional<Favorite> favorite = favoriteRepository.findByUserIdAndPostId(userId, post.getId());
            dto.setIsFavorited(favorite.isPresent());
            
            return dto;
        }).collect(Collectors.toList());
        
        Map<String, Object> response = Map.of(
            "posts", postDTOs,
            "currentPage", postPage.getNumber(),
            "totalItems", postPage.getTotalElements(),
            "totalPages", postPage.getTotalPages()
        );
        
        return ResponseEntity.ok(response);
    }

    /**
     * 管理员API：修复所有帖子的点赞和收藏计数
     */
    @PostMapping("/admin/reset-counts")
    @Transactional
    public ResponseEntity<Map<String, Object>> resetAllPostCounts(
            @RequestParam Long userId) {
        
        Optional<User> userOpt = userRepository.findById(userId);
        if (!userOpt.isPresent() || userOpt.get().getIsAdmin() == null || userOpt.get().getIsAdmin() != 1) {
            return ResponseEntity.status(403).build();
        }
        User user = userOpt.get();
        
        System.out.println("管理员 " + user.getUsername() + " 正在重置所有帖子的计数");
        
        try {
            // 获取所有帖子
            List<Post> allPosts = postRepository.findAll();
            int fixedCount = 0;
            
            for (Post post : allPosts) {
                boolean needsUpdate = false;
                
                // 修复点赞数
                long actualLikeCount = likeRepository.countByPostId(post.getId());
                if (actualLikeCount != post.getLikeCount()) {
                    System.out.println("帖子 " + post.getId() + " 的点赞数不一致，从 " + 
                                   post.getLikeCount() + " 改为 " + actualLikeCount);
                    post.setLikeCount((int)actualLikeCount);
                    needsUpdate = true;
                }
                
                // 修复收藏数
                long actualFavoriteCount = favoriteRepository.countByPostId(post.getId());
                if (actualFavoriteCount != post.getFavoriteCount()) {
                    System.out.println("帖子 " + post.getId() + " 的收藏数不一致，从 " + 
                                   post.getFavoriteCount() + " 改为 " + actualFavoriteCount);
                    post.setFavoriteCount((int)actualFavoriteCount);
                    needsUpdate = true;
                }
                
                // 修复评论数
                long actualCommentCount = commentRepository.countByPostId(post.getId());
                if (actualCommentCount != post.getCommentCount()) {
                    System.out.println("帖子 " + post.getId() + " 的评论数不一致，从 " + 
                                   post.getCommentCount() + " 改为 " + actualCommentCount);
                    post.setCommentCount((int)actualCommentCount);
                    needsUpdate = true;
                }
                
                if (needsUpdate) {
                    postRepository.save(post);
                    fixedCount++;
                }
            }
            
            String message = "计数重置完成，共修复 " + fixedCount + " 个帖子的计数。";
            System.out.println(message);
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "message", message,
                "fixedCount", fixedCount,
                "totalPosts", allPosts.size()
            ));
            
        } catch (Exception e) {
            System.err.println("重置计数时发生错误: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(500).body(Map.of(
                "error", "重置计数时发生错误",
                "message", e.getMessage()
            ));
        }
    }
} 